from numpy import polynomial

from pynumpak.type import Interval, func_t


def gauss_legendre(f: func_t, ab: Interval, n: int, m: int = 5):
    """分为 n 段后, 利用 m 点 Gauss-Legendre 公式"""
    a, b = ab
    interval = (b - a) / n
    x, w = polynomial.legendre.leggauss(m)
    s = 0
    for i in range(n):
        for j in range(len(x)):
            s += w[j] * f(a + (2 * i + x[j] + 1) / 2 * interval) * interval / 2
    return s
